/**
 * 
 */
package ar.rhok.yerbus.core.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import ar.rhok.yerbus.core.dao.NeedDAO;
import ar.rhok.yerbus.core.dao.RequestDAO;
import ar.rhok.yerbus.core.dao.UserDAO;
import ar.rhok.yerbus.core.domain.Entity;
import ar.rhok.yerbus.core.domain.Need;
import ar.rhok.yerbus.core.domain.Request;
import ar.rhok.yerbus.core.domain.User;
import ar.rhok.yerbus.core.services.NeedService;
import ar.rhok.yerbus.core.services.RequestPublisher;

/**
 * @author Mauro Monti
 *
 */
@Service
@Transactional
public class NeedServiceImpl implements NeedService {

	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private NeedDAO needDAO;
	
	@Autowired
	private RequestDAO requestDAO;
	
	@Autowired
	private RequestPublisher requestPublisher;

	@Override
	public Need createNeed(Long pEntityId, String pDescription) {
		final Entity entity = new Entity();
		entity.setId(pEntityId);
		
		final Need need = new Need();
		need.setEntity(entity);
		need.setDescription(pDescription);
		return needDAO.save(need);
	}

	@Override
	public Request createRequest(Long pNeedId, String pDescription, String pFeedbackMessage) {
		final Need need = new Need();
		need.setId(pNeedId);
		
		final Request request = new Request();
		request.setNeed(need);
		request.setDescription(pDescription);
		request.setFeedbackMessage(pFeedbackMessage);
		
		return this.requestDAO.save(request);
	}

	@Override
	public void userAcceptRequest(Long pIdRequest, Long pUserId) {
		final Request request  = this.requestDAO.findById(pIdRequest);
		final User user  = this.userDAO.findById(pUserId);
		
		user.getRequests().add(request);
	}

	@Override
	public void requestCompleted(Long pIdRequest, Long pUserId) {
		final Request acceptedRequest  = this.requestDAO.findById(pIdRequest);
		final User user  = this.userDAO.findById(pUserId);
		
		user.getRequests().remove(acceptedRequest);
		
		this.requestPublisher.publishFeedBack(acceptedRequest, user);
	}
	
}
